(function(){
	"use strict";
	
	var $qryForm,
		$resultContainer,
		$treeContainer;
	var $totalRowsEL,$pageNoEL,$totalPagesEL,$pageSizeEL;
	var	$paginationBoxEL;
	var	$firstPageLink,$lastPageLink,$previousPageLink,$nextPageLink;
	
	$(function(){
		$treeContainer=$("#functionalityTableTree");
		
		$qryForm=$("#qryForm");
		$resultContainer=$("#resultContainer");
		$totalRowsEL=$("#totalRowsEL");
		$pageNoEL=$("#pageNoEL");
		$totalPagesEL=$("#totalPagesEL");
		$pageSizeEL=$("#pageSizeEL");
		$paginationBoxEL=$("#paginationBoxEL");
		
		$firstPageLink=$("#firstPageLink");
		$lastPageLink=$("#lastPageLink");
		$previousPageLink=$("#previousPageLink");
		$nextPageLink=$("#nextPageLink");
	
		
		$qryForm.submit(handleFormSubmit).submit();
	})	
	
	
	
	var handleFormSubmit=function(evt){
		var url="/api/doc/list";
		$.get(url,$qryForm.serialize(),function(resp){
			if(resp.code==="ok"){
				if(resp.data.length===0){
					notFound();
				}else{
				var result=resp.data;
				result=list2tree(result);
				console.log(result);
				paintTree(result);
				}
			}
		});
		return false;
	}
	
	var paintTree=function(data){
		$treeContainer.fancytree({
			icon:false,
			minExpandLevel:1,
			extensions:["table"],
			table:{
				nodeColumnIdx:1,
				indentation:16
			},
			source:data,
			renderColumns:function(evt,evtData){
				//node对象
				var node=evtData.node;
				//我们传入的node模型
				var nodeData=node.data;
				//tr标签
				var tr=node.tr;
				var tds=tr.cells;
				
				//第一列序号
				tds[0].textContent=node.getIndexHier();
				//第二列名字
				tds[2].innerHTML="<a href=''>查看"+"</a>";
				tds[3].textContent=$$(nodeData.savePath);
				tds[4].textContent=Date.format(nodeData.createTime);
			}
		});
	};
	
	var list2tree=function (list) {
		//保存所有根节点
		var roots=[];
		//保存所有节点
		var nodeMap={};
		
		list.filter(function(node){
			node.key=node.id;
			node.title=node.name;
			nodeMap[node.id]=node;
			//如果父节点id未定义或未null,则表示未跟节点
			if(node.parentId===null||typeof node.parentId==="undefined"){
				roots.push(node);
				return false;
			}
			return true;
		}).forEach(function(node){
			//找到父节点
			var parent=nodeMap[node.parentId];
			if(parent){
				if(!parent.children){
					parent.children=[];
				}
				parent.children.push(node);
			}else{
				//未找到父节点
				console.error("节点"+node+"未找到父节点");
			}
		});
		return roots;
	};
	
	var notFound=function(){
		var html="<tr>";
			html+="<td colspan='999999'>抱歉没有找到数据</td>";
			html+="</tr>";
		$resultContainer.html(html);
	}
		
})()
